package com.example.client

import android.util.Log
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.WebSocket
import okhttp3.WebSocketListener
import java.util.Timer
import java.util.TimerTask

class WebSocketClient {

   val client by lazy { OkHttpClient() }

    lateinit var webSocket: WebSocket
    fun init(listener: WebSocketListener) {
        val build = Request.Builder()
            .url("ws://localhost:8082")
            .build()
        webSocket = client.newWebSocket(build,listener)

    }


    fun heartBeat(){
        Timer().scheduleAtFixedRate(object :TimerTask(){
            override fun run() {
                sendMessage("心跳包")
                Log.e("hzb","发送心跳包")
            }

        },0,4000)
    }
    fun sendMessage(msg:String){
        if (!::webSocket.isInitialized){
            throw Exception("请先初始化start()方法")
        }
        webSocket.send(msg)
    }

    companion object{
        private var instance:WebSocketClient?=null

        fun getInstance():WebSocketClient{
            if (instance==null){
                instance= WebSocketClient()
            }
            return instance!!
        }
    }
}